package com.itheima.bakery.demos.web.service;

import com.itheima.bakery.demos.web.Repositories.*;
import com.itheima.bakery.demos.web.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
@Service
public class SearchService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private InventoryRepository inventoryRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;

    public List<Object> globalSearch(String keyword) {
        List<User> users = userRepository.findBynameContainingOrEmailContaining(keyword, keyword);
        List<Product> products = productRepository.findByNameContaining(keyword);
        List<Order> orders = orderRepository.findByOrderIDContaining(keyword);
        List<Inventory> inventory = inventoryRepository.findByProductIDContaining(keyword);
        List<OrderDetail> orderDetails=new ArrayList<>();
        List<Object> results = new ArrayList<>();
        results.addAll(users);
        results.addAll(products);
        results.addAll(orders);
        results.addAll(inventory);

        try {
            Long productId = Long.parseLong(keyword);
           orderDetails = orderDetailRepository.findByProductId(productId);
            results.addAll(orderDetails);
        } catch (NumberFormatException e) {
            // 如果关键字不是有效的数字，不进行订单详细搜索
        }

        results.addAll(orderDetails);
        return results;
    }
}
